// 解决300ms延迟
FastClick.attach(document.body)

let myAudio = document.querySelector('#myAudio'),
    musicBtn = document.querySelector('.music-btn'),
    titleBox = document.querySelector('.base-info .title'),
    authorBox = document.querySelector('.base-info .author'),
    picBox = document.querySelector('.base-info .pic'),
    wrapperBox = document.querySelector('.wrapper'),
    lyricList = [],
    alreadyBox = document.querySelector('.already'),
    durationBox = document.querySelector('.duration'),
    rateBox = document.querySelector('.rate')

// 处理播放时间和进度的
const format = function format(num){
    let minutes = Math.floor(num/60),
        seconds = Math.ceil(num - minutes*60)
        if(minutes < 10 )minutes = '0'+ minutes
        if(seconds < 10 )seconds = '0'+ seconds
        return `${minutes}:${seconds}`
}
const handleTimeAndRate = function handleTimeAndRate(){
    let {currentTime,duration} = myAudio
    if(isNaN(currentTime) || isNaN(duration))return
    if(currentTime >= duration){
        currentTime = 0
    }
    alreadyBox.innerHTML = format(currentTime)
    durationBox.innerHTML = format(duration)
    rateBox.style.width = `${currentTime/duration*100}%`
}

// audio 加载完毕基础信息
myAudio.onloadedmetadata = handleTimeAndRate
$sub.on('music',handleTimeAndRate)

/* 获取歌词绑定数据 */
const render = function render(lyric){
   //解析标题和作者
   let title =  lyric.match(/\[ti&#58;([^\]]+)\]/),
       author =  lyric.match(/\[ar&#58;([^\]]+)\]/)
   if(title)titleBox.innerHTML = title[1]
   if(author)authorBox.innerHTML = author[1]

   // 解析歌词
   let arr = []
   lyric = lyric.replace(/&#(\d+);/g,(val,num)=>{
        let text = ''
        switch(+num){
            case 32 : 
                text = ' '
                break
            case 40 :
                text = '('
                break
            case 41 :
                text =')'
                break
            case 45 :
                text = '-'
                break
            default:
                text = val
        }
        return text
   })
   lyric.replace(/\[(\d+)&#58;(\d+)&#46;(?:\d+)\]([^&#;]+)(&#10;)?/g, (_, minutes, seconds, text) => {
        arr.push({
            minutes,
            seconds,
            text
        })
    })
    
    // 歌词绑定
    let str = ``
    arr.forEach(item=>{
        let {minutes,seconds,text} = item
        str += `<p minutes="${minutes}" seconds="${seconds}">${text}</p> `
    })
    wrapperBox.innerHTML = str

    // 其他操作
    musicBtn.style.display = 'block'
    picBox.style.display = 'block'
    lyricList = Array.from(wrapperBox.querySelectorAll('p'))

}

const queryData =function queryData(){
    return new Promise(resolve => {
        let xhr = new XMLHttpRequest;
        xhr.open('GET', './json/lyric.json');
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = JSON.parse(xhr.responseText);
                resolve(data);
            }
        };
        xhr.send();
    });
}
queryData().then(value=>{
    return value.lyric
}).then(lyric=>{
    render(lyric)
})


// 音乐的播放暂停
// 控制歌词对应
let n = 0
$sub.on('music',function(){
    let {currentTime,duration} = myAudio,
        [minutes,seconds] = format(currentTime).split(':'),
        H = lyricList[0].offsetHeight

    let matchArr = [],
        matchNoneArr = []
    lyricList.forEach(item=>{
        let a = item.getAttribute('minutes'),
            b = item.getAttribute('seconds')
        if(a === minutes && b === seconds){
           matchArr.push(item)
            return
        }
        matchNoneArr.push(item)
    })
    // 发现匹配再处理
    if(matchArr.length > 0 ){
        matchArr.forEach(item=>item.classList.add('active'))
        matchNoneArr.forEach(item=>item.classList.remove('active'))
        // 匹配的同时不要忘记：wrapper的挪动
        n += matchArr.length
        if(n > 4){
            wrapperBox.style.transform = `translateY(${-(n-4)*H}px)`
        }
    }
    // 播放完毕处理
    if(currentTime >= duration){
        myAudio.pause()
        musicBtn.classList.remove('move')
        wrapperBox.style.transform = `translateY(0)`
        lyricList.forEach(item=>item.classList.remove('active'))
        n = 0
        if(timer){
            clearInterval(timer)
            timer = null 
        }
    }
})

let timer = null
musicBtn.onclick = function (){
    if(myAudio.paused){
        // 当前是暂停的：我们要播放
        myAudio.play()
        musicBtn.classList.add('move')
        if(!timer){
            $sub.emit('music')
            timer = setInterval(() => {
                $sub.emit('music')
            }, 1000);
        }
        return
    }
    // 当前是播放的：我们要暂停
    myAudio.pause()
    musicBtn.classList.remove('move')
    if(timer){
        clearInterval(timer)
        timer = null
    }
}
